package com.ksframework.common.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 提供常用String类型数据工具. <p>
 * 该类继承了apache 的StringUtils，可以自行扩展.<p>
 * apache StringUtils的常用方法：<p>
 * <code>public static boolean isEmpty(String str) </code>: 判断某字符串是否为空，为空的标准是str==null或str.length()==0 <p>
 * <code>public static boolean isNotEmpty(String str) </code>: 判断某字符串是否非空，等于!isEmpty(String str) <p>
 * <code>public static boolean isBlank(String str) </code> : 判断某字符串是否为空或长度为0或由空白符(whitespace)构成 <p>
	<code>public static String trim(String str) </code>:   去掉字符串两端的控制符(control characters, char <= 32),如果输入为null则返回null<p> 
    <code>public static String trimToNull(String str) </code>:   去掉字符串两端的控制符(control characters, char <= 32),如果变为null或""，则返回null <p>
    <code>public static String trimToEmpty(String str) </code>:  去掉字符串两端的控制符(control characters, char <= 32),如果变为null或""，则返回"" <p>
	<code>public static String strip(String str) </code>:   去掉字符串两端的空白符(whitespace)，如果输入为null则返回null <p>
	<code>public static String stripToNull(String str) </code>:  去掉字符串两端的空白符(whitespace)，如果变为null或""，则返回null <p>
 	<code>public static String stripToEmpty(String str)</code>:   去掉字符串两端的空白符(whitespace)，如果变为null或""，则返回"" <p>
	<code>public static String strip(String str, String stripChars) </code>:  去掉str两端的在stripChars中的字符。 如果str为null或等于""，则返回它本身；如果stripChars为null或""，则返回strip(String str)。 <p>
    <code>public static String stripStart(String str, String stripChars) </code>:  和以上相似，去掉str前端的在stripChars中的字符。 <p>
    <code>public static String stripEnd(String str, String stripChars) </code>:   和以上相似，去掉str末端的在stripChars中的字符。 <p>
    <code> public static String[] stripAll(String[] strs) </code>: 对字符串数组中的每个字符串进行strip(String str)，然后返回。 如果strs为null或strs长度为0，则返回strs本身 <p>
    <code>public static String[] stripAll(String[] strs, String stripChars) </code>:  对字符串数组中的每个字符串进行strip(String str, String stripChars)，然后返回。    如果strs为null或strs长度为0，则返回strs本身 <p>
    <code> public static boolean equals(String str1, String str2) </code>: 比较两个字符串是否相等，如果两个均为空则也认为相等。<p> 
    <code>public static boolean equalsIgnoreCase(String str1, String str2) </code>: 比较两个字符串是否相等，不区分大小写，如果两个均为空则也认为相等。<p> 
    <code>public static int indexOf(String str, char searchChar) </code>: 返回字符searchChar在字符串str中第一次出现的位置。 如果searchChar没有在str中出现则返回-1， 如果str为null或""，则也返回-1 <p>
    <code>public static int indexOf(String str, char searchChar, int startPos)</code>:  返回字符searchChar从startPos开始在字符串str中第一次出现的位置。 <p>
	更多方法请参见apche utils api文档。
 * 
 * @see  org.apache.commons.lang.StringUtils
 * @see  org.springframework.util.StringUtils
 * @author： Snoopy Chen (ctfzh@yahoo.com.cn)
 * @since： 2009-2-25 
 * @version 1.0
 */
public class StringUtil extends org.apache.commons.lang.StringUtils{
	
	/**定义HTML escape 替换字符*/
	 private final static byte[] val = { 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x00, 0x01,       
         0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F }; 
	
	/**
	 * 随即生产随即数，可以用来生产tocken字符串等.
	 * @param length 生成长度
	 * @return 随即数字符串.
	 */
	public static String getRandomString(int length) {
		StringBuffer bu = new StringBuffer();
		String[] arr = { "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
				"m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
				"H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
		Random random = new Random();
		while (bu.length() < length) {
			String temp = arr[random.nextInt(57)];
			if (bu.indexOf(temp) == -1) {
				bu.append(temp);
			}
		}
		return bu.toString();
	}
	
	/**
	 * 获取某个区间的随机整数.
	 * @param sek 随机种子
	 * @param min 最小整数
	 * @param max 最大整数
	 * @return 随机整数
	 */
	public static int getRandomInt(int sek, int min, int max) {
		Random random = new Random();
		int temp = 0;
		do {
			temp = random.nextInt(sek);
		} while (temp < min || temp > max);
		return temp;
	}
	
	/**
	 * 实现了js 版本的unescape方法.<p>
	 * 用于前台JS对传入的参数做了escape，JAVA后台取到参数后需要unescape。
	 * @param s
	 * @return
	 */
	 public static String unescape(String s) {       
         StringBuffer sbuf = new StringBuffer();       
         int i = 0;       
         int len = s.length();       
         while (i < len) {       
         int ch = s.charAt(i);       
         if ('A' <= ch && ch <= 'Z') {   
         sbuf.append((char) ch);       
         } else if ('a' <= ch && ch <= 'z') {        
         sbuf.append((char) ch);       
         } else if ('0' <= ch && ch <= '9') {    
             sbuf.append((char) ch);       
         } else if (ch == '-' || ch == '_'|| ch == '.' || ch == '!' || ch == '~' || ch == '*'|| ch == '\'' || ch == '(' || ch == ')') {       
         sbuf.append((char) ch);       
         } else if (ch == '%') {   
             int cint = 0;       
             if ('u' != s.charAt(i + 1)) {       
             cint = (cint << 4) | val[s.charAt(i + 1)];       
             cint = (cint << 4) | val[s.charAt(i + 2)];       
             i += 2;       
             } else {       
                 cint = (cint << 4) | val[s.charAt(i + 2)];       
                 cint = (cint << 4) | val[s.charAt(i + 3)];       
                 cint = (cint << 4) | val[s.charAt(i + 4)];       
                 cint = (cint << 4) | val[s.charAt(i + 5)];       
                 i += 5;       
             }       
             sbuf.append((char) cint);   
         } else {       
             sbuf.append((char) ch);       
         }       
         i++;       
         }       
         return sbuf.toString();       
	 }  
	 
	 
	 public static enum ENCODING {
			GBK, UTF_8, ISO_8859_1;
		}
		/**
		 * @作用:null 或者 'null' 转换成 ""
		 */
		public static final String nullToEmpty(Object str) {
			return (((null == str) || ("null".equals(str))) ? "" : str.toString());
		}

		/**
		 * @作用:判断是否为数字
		 */
		public static boolean isNumeric(String str) {
			Matcher isNum = Pattern.compile("(-|\\+)?[0-9]+(.[0-9]+\\+)?").matcher(str);
			return isNum.matches();
		}

		public static Integer parseInt(Object str) {
			return str == null ? 0 : Integer.valueOf((isNumeric(str.toString())) ? Integer.parseInt(str.toString()) : 0);
		}

		public static Float parseFloat(Object str) {
			try {
				return Float.valueOf(Float.parseFloat(str.toString()));
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return Float.valueOf(0.0F);
		}

		public static Double parseDouble(Object str) {
			try {
				return Double.valueOf(Double.parseDouble(str.toString()));
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return Double.valueOf(0.0D);
		}

		public static Boolean parseBoolean(Object str) {
			String s = str.toString().toLowerCase();
			if (("y".equalsIgnoreCase(s)) || ("yes".equalsIgnoreCase(s)) || ("true".equalsIgnoreCase(s)) || ("t".equalsIgnoreCase(s)) || ("1".equalsIgnoreCase(s))) {
				return true;
			}
			return false;
		}

		public static double formatDoubleValue(int medianAfterTheDecimalPoint, String doubleStringValue) {
			Double doubleValue = Double.valueOf(doubleStringValue);
			return new BigDecimal(doubleValue.doubleValue()).setScale(medianAfterTheDecimalPoint, BigDecimal.ROUND_HALF_UP).doubleValue();
		}

		public static String formatAnyseValue(String formatExpression, Object value) {
			DecimalFormat df = new DecimalFormat(formatExpression);
			return df.format(value);
		}

		/**
		 * @作用: 字符编码转换
		 */
		public static String fromEncodingToAnotherEncoding(String content, ENCODING fromEncoding, ENCODING toEncoding) {
			String from = fromEncoding.toString().replace("_", "-");
			String to = toEncoding.toString().replace("_", "-");
			if (null != content)
				try {
					byte[] tmpbyte = content.getBytes(from);
					content = new String(tmpbyte, to);
				} catch (Exception e) {
					System.out.println("Error: from: " + from + " To: " + to + " :" + e.getMessage());
				}

			return content;
		}

		/**
		 * @作用:转换成html编码
		 */
		public static String htmlEncode(String txt) {
			if (null != txt) {
				txt = txt.replace("&", "&amp;")
						.replace("&amp;amp;", "&amp;")
						.replace("&amp;quot;", "&quot;")
						.replace("\"", "&quot;")
						.replace("&amp;lt;", "&lt;")
						.replace("<", "&lt;")
						.replace("&amp;gt;", "&gt;")
						.replace(">", "&gt;")
						.replace("&amp;nbsp;", "&nbsp;");
			}
			return txt;
		}

		/**
		 * @作用:去除html编码
		 */
		public static String unHtmlEncode(String txt) {
			if (null != txt) {
				txt = txt.replace("&amp;", "&")
						.replace("&quot;", "\"")
						.replace("&lt;", "<")
						.replace("&gt;", ">")
						.replace("&nbsp;", " ");
			}
			return txt;
		}

		/**
		 * @作用:转换字符串首字母,默认是转换成小写字母,如boolean... bs 设置成true 转大写
		 */
		public static String firstChar2xCase(String str, boolean... bs) {
			if ((null == str) || ("".equalsIgnoreCase(str))) {
				return "";
			}
			return ((bs.length == 0) ? str.substring(0, 1).toLowerCase() : str.substring(0, 1).toUpperCase()).concat(str.substring(1));
		}

//		/**
//		 * @作用:产生一个指定长度的随机字符串
//		 */
//		public static String getRandomString(int strLength) {
//			char[] c = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q',
//					'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd',
//					'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm' };
//			Random random = new Random();
//			StringBuffer sb = new StringBuffer();
//			for (int j = 0; j < strLength; ++j) {
//				sb.append(c[(java.lang.Math.abs(random.nextInt()) % c.length)]);
//			}
//			return sb.toString();
//		}
		
}